package com.fattree.file.word.service.impl;

import com.fattree.file.word.bean.Word;
import com.fattree.file.word.service.ExportWordService;
import com.fattree.file.word.utils.DataUtils;
import com.fattree.file.word.utils.WordUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;

@Service
public class ExportWordServiceImpl implements ExportWordService {
    private static String charset = "UTF-8";

    @Override
    public void exportDocWord(HttpServletResponse response, String extName) {
        try {
            Word word = DataUtils.getWord(extName);
            WordUtils.getWordDocOutputStream(word);
            if (word != null) {
                response.setCharacterEncoding(charset);
                response.setHeader("Content-Disposition", "attachment;filename=" + word.getDocName());
                response.setContentType("file");

                ByteArrayInputStream inputStream = new ByteArrayInputStream(WordUtils.getWordDocOutputStream(word).toByteArray());
                BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                byte[] buffer = new byte[inputStream.available() + 1024];
                int num = 0;
                /**
                 * 将数据读取到缓冲区中，再将缓冲区中数据传输出去
                 */
                while ((num = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, num);
                }
                inputStream.close();
                outputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
